package itsen.com.bduidemo.modle.md.palette;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import itsen.com.bduidemo.R;
import itsen.com.bduidemo.common.activity.BaseAppActivity;
import itsen.com.bduidemo.lib.tool.LogTool;
import itsen.com.bduidemo.lib.tool.ToastTool;
import itsen.com.bduidemo.lib.widget.LSwipeRefreshLayout;
import itsen.com.bduidemo.modle.md.transitionanim.TransitionActivity2;

public class PaletteActivity extends BaseAppActivity {

    @BindView(R.id.rv_list)
    RecyclerView mRecycleView;
    @BindView(R.id.lsrl)
    LSwipeRefreshLayout mLsrfl;

    private Handler mHandler;
    private AdapterGoods adapter;
    final List<Goods> list = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_palette;
    }

    @Override
    public void initData() {

        for (int i = 0; i < imgUrl.length; i++) {
            Goods goods = new Goods();
            goods.logoUrl = imgUrl[i];
            goods.name = names[i];
            goods.price = "¥" + (67 + i);
            goods.countAndCompoment = "月销售120分  好评率96%";
            list.add(goods);
        }

        adapter = new AdapterGoods(list, this);
        adapter.setOnitemClickListener(new AdapterGoods.OnitemClickListener() {
            @Override
            public void itemClick(View v, int position, ActivityOptionsCompat comapt) {
                Intent intent = new Intent(PaletteActivity.this, PaletteActivity2.class);
                intent.putExtra("logoUrl", list.get(position).logoUrl);
                intent.putExtra("name", list.get(position).name);

                ImageView imageView = (ImageView) v;
                Drawable drawable = imageView.getDrawable();
                if (drawable != null) {
                    getRgb(drawable, intent, comapt);
                } else {
                    //跳转
                    ActivityCompat.startActivity(PaletteActivity.this, intent, comapt.toBundle());
                }
            }
        });
        mRecycleView.setLayoutManager(new GridLayoutManager(this, 2));
        mRecycleView.setAdapter(adapter);
        setmLsrfl();
        setmRecycleViewL();
    }

    int color;

    private int getRgb(Drawable drawable, final Intent intent, final ActivityOptionsCompat comapt) {
        if (drawable != null) {
            LogTool.e("drable");
            GlideBitmapDrawable bd = (GlideBitmapDrawable) drawable;
            Bitmap bitmap = bd.getBitmap();
            //异步方式
            Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
                @Override
                public void onGenerated(Palette palette) {
                    Palette.Swatch vibrantLight = palette.getLightVibrantSwatch();//有活力的，亮色
                    Palette.Swatch vibrantDark = palette.getDarkMutedSwatch();//柔和的，暗色
                    try {
                        color = vibrantLight.getRgb();
                    }catch (Exception e){
                        color = vibrantDark.getRgb();
                    }
                    intent.putExtra("color", color);
                    ActivityCompat.startActivity(PaletteActivity.this, intent, comapt.toBundle());
                    LogTool.e("drable:" + color);
                }
            });
        }
        return color;
    }

    /**
     * 下拉刷新初始化
     */
    private void setmLsrfl(){
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        mLsrfl.setRefreshing(false);
                        ToastTool.showShort("刷新完成");
                        break;
                    case 2:
                        addFooterData();
                        ToastTool.showShort("加载完成");
                        adapter.changeMoreStatus(AdapterGoods.NO_LOAD_MORE);
                        break;
                }
            }
        };
        mLsrfl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message message = new Message();
                message.what = 1;
                mHandler.sendMessageDelayed(message,500);
               // mHandler.sendEmptyMessage(2);
            }
        });
    }

    private void setmRecycleViewL(){
        mRecycleView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem ;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                adapter.changeMoreStatus(AdapterGoods.LOADING_MORE);
                //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
                if (newState==RecyclerView.SCROLL_STATE_IDLE&&lastVisibleItem+1==adapter.getItemCount()){
                    //执行加载数据

                    Message message = new Message();
                    message.what = 2;
                    mHandler.sendMessageDelayed(message,1000);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem=gridLayoutManager.findLastVisibleItemPosition();
            }
        });
    }

    private void addFooterData(){
        for (int i = 0; i < 5; i++) {
            List<Goods> lists = new ArrayList<>();
            Goods goods = new Goods();
            goods.logoUrl = imgUrl[i];
            goods.name = names[i];
            goods.price = "¥" + (67 + i);
            goods.countAndCompoment = "月销售120分  好评率96%";
            lists.add(goods);
            adapter.AddFooterItem(lists);
        }
    }

    private String imgUrl[] = {
            "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2483150767.jpg",
            "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2502013123.jpg",
            "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2493581990.jpg",
            "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2500155563.jpg",
            "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2502222821.jpg",
            "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2496995622.jpg",
            "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2502553277.jpg",
            "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2502663075.jpg",
            "https://img3.doubanio.com/view/photo/m/public/p2500126054.jpg",
            "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2501652013.jpg"
    };

    private String names[] = {
            "高丽得劲", "美丽的世界", "ADDEGD", "HER GOOD FOE", "ANDR GGS", "东方", "我们", "到底", "到底", "三色饭"
    };
}
